import axios, {
  // AxiosRequestConfig,
  AxiosError
} from 'axios'

import qs from 'qs'

import { config } from './config'
import { message } from 'ant-design-vue';
import { getToken } from '@/utils/token'
import { useCache } from '@/hooks/web/useCache'
import router from '@/router'
import { getLanguage } from '..';
import { getFingerprint } from '../fingerprintjs';

const { result_code, base_url } = config

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASEPATH, // api 的 base_url
  timeout: 60000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  async (config) => {
    // 设置token
    const token = getToken();
    config.headers.Authorization = `Bearer ${token}`;
     // 浏览器指纹
     const fingerprint = await getFingerprint();
     if (fingerprint) {
       config.headers['Finger-Print'] = fingerprint;
     }

    const lang = getLanguage();
    config.headers['Locale'] = lang;

    if (
      config.method === 'post' &&
      config.headers['Content-Type'] ===
        'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }

    // 添加时区偏移值
    config.headers['TimeZone-Offset'] = (new Date).getTimezoneOffset();

    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    
    return config
  },
  (error: AxiosError) => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response) => {
    const data = response.data || {};

    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (data.error && data.error.message) { // 有错误提示返回，优先返回错误内容
      message.error(data.error.message)
    } else if (data.code === result_code) {
      return response.data
    } else if (response.status === 200) {
      return response.data
    } else {
      message.error(response.data.message)
    }
  },
  (error: AxiosError) => {
    const data: any = error?.response?.data || {};
    let msg = error.message;
    if (data && data.error && data.error.code === 9999) { // 授权失效，删除token，重定向到登录页面
      // message.error('登录信息已过期，请重新登录~')
      const { wsCache } = useCache()

      wsCache.clear()
      // router.push({
      //   name: 'Login'
      // });
      return;
    }

    if (data && data.error && data.error.message) {
      msg = data.error.message
    }
    message.error(msg)
    return Promise.reject(error)
  }
)

export { service }
